import { Component, OnInit, ViewChild, ElementRef, Input } from '@angular/core';
import { SafeResourceUrl, DomSanitizer } from '@angular/platform-browser';
import { Subscription, BehaviorSubject } from 'rxjs';
import { LoadingService } from '../../service/loading.service';
import { MetadataService } from '../../service/metadata.service';
import { ThemeRouteChangeService } from '../../service/theme-route-change.service';

@Component({
    selector: 'app-iframe',
    templateUrl: './iframe.component.html',
    styleUrls: ['./iframe.component.css']
})
export class IframeComponent implements OnInit {
    @ViewChild('iframe') iframe: ElementRef;

    private _previewType = '';

    /**
     * pType: preview-page 预览模板| preview-widget 预览组件
     */
    @Input()
    set previewType(pType: string) {
        // 预览类型
        if (pType !== this._previewType) {
            this._previewType = pType;
            this.url = document.getElementsByTagName('base')[0].href + pType + '/' + this.themeRouteChangeSer.getFormatUrl();
            this.iframeUrl = this.sanitizer.bypassSecurityTrustResourceUrl(this.url);
        }
    }

    get previewType() {
        return this._previewType;
    }

    url: string;

    iframeUrl: SafeResourceUrl;

    cssSubscription: Subscription;

    widgetSubscription: Subscription;

    theme: string;

    widgetName = new BehaviorSubject<string>('');

    constructor(
        private sanitizer: DomSanitizer,
        private metadataService: MetadataService,
        private loading: LoadingService,
        private themeRouteChangeSer: ThemeRouteChangeService
    ) {
        this.loading.show();
        this.themeRouteChangeSer.getUrlChange().subscribe((url) => {
            // Url变更
            if (this.previewType) {
                this.url = document.getElementsByTagName('base')[0].href + this.previewType + '/' + url;
                this.iframeUrl = this.sanitizer.bypassSecurityTrustResourceUrl(this.url);
            }
        });
        // this.route.params.subscribe((params) => {
        //     debugger
        //     const widget = params['previewType'];

        //     this.url = document.getElementsByTagName('base')[0].href + 'preview-page';
        //     this.iframeUrl = this.sanitizer.bypassSecurityTrustResourceUrl(this.url);
        //     //   if(this.widgetName.getValue() !== widget) {
        //     //       this.widgetName.next(widget);
        //     //   }
        //     //   if(this.theme !== params['theme']) {
        //     //       this.loading.show();
        //     //       this.theme = params['theme'];
        //     //       this.url = document.getElementsByTagName('base')[0].href + (widget ? 'preview' : 'wizard') + '/' + this.theme;
        //     //       this.iframeUrl = this.sanitizer.bypassSecurityTrustResourceUrl(this.url);
        //     //   }
        // });
    }

    receiveMessage(e): void {
        if (e.data && e.data.hideLoading) {
            this.onIframeLoad();
            this.loading.hide();
        }
    }

    /**
     * iframe加载成功后
     */
    onIframeLoad(): void {
        const frameWindow = this.iframe.nativeElement.contentWindow;

        if (frameWindow === null) return;

        if (this.cssSubscription) this.cssSubscription.unsubscribe();

        this.cssSubscription = this.metadataService.css.subscribe(({ css, theme }) => {
            theme = theme || this.metadataService.theme;
            const { name } = theme;
            const themeSize = theme.colorScheme.includes('loose') ? 'loose' : 'default';
            // iFrame窗口 发出消息事件
            frameWindow.postMessage(
                {
                    css,
                    name,
                    themeSize
                },
                this.url
            );
        });
    }

    ngOnDestroy(): void {
        if (this.cssSubscription) this.cssSubscription.unsubscribe();
    }

    ngOnInit(): void {
        // 给window绑定事件
        // 收到来自子内容的事件
        window.addEventListener('message', this.receiveMessage.bind(this), false);
    }
}
